package com.shop.shoppingmall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.shoppingmall.dao.*;
import com.shop.shoppingmall.entity.*;
import com.shop.shoppingmall.service.ShProductService;
import com.shop.shoppingmall.util.JwtUtil;
import com.shop.shoppingmall.util.RealUtil;
import com.shop.shoppingmall.util.UUIDGenerator;
import com.shop.shoppingmall.util.api.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.TTCCLayout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (ShProduct)表服务实现类
 *
 * @author makejava
 * @since 2020-09-07 17:09:21
 */
@Service("shProductService")
@Slf4j
@CrossOrigin
@Transactional
public class ShProductServiceImpl implements ShProductService {
    @Resource
    private ShProductDao shProductDao;
    @Resource
    private ShProductSpecsDao shProductSpecsDao;
    @Resource
    private TSkuDao tSkuDao;
    @Resource
    private ShMerchantDao shMerchantDao;
    @Resource
    private ShUserDao shUserDao;
    @Resource
    private ShFollowProductDao shFollowProductDao;
    @Resource
    private ShFollowShopDao shFollowShopDao;
    @Resource
    private  ShShopCartDao shShopCartDao;
    @Resource
    private ShBackUserDao shBackUserDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShProduct queryById(String id) {
        return this.shProductDao.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param // 实例对象
     * @return 实例对象
     */
    @Override
    public Result insert(List<ShProduct> shProducts, List<ShProductSpecs> list,List<ShopSpecs> shopSpecs) {
        String  id = UUIDGenerator.generate();
        String xx = "";
        for(ShopSpecs shopSpecs1 : shopSpecs){
            String a =  shopSpecs1.getChildren();
            String b= shopSpecs1.getType();
            xx = xx+","+ '"'+b +'"'+":"+a;
        }
        String str1=xx.substring(0, xx.indexOf(","));
        String str2=xx.substring(str1.length()+1, xx.length());
        for(int i = 0;i<shProducts.size();i++){
            ShProduct  shProduct =  shProducts.get(i);
            shProduct .setId(id);
            shProduct.setAttributeList('{'+str2+'}');
            shProductDao.insert(shProduct);
        }
        for(ShProductSpecs shProductSpecs : list){
            shProductSpecs.setId(UUIDGenerator.generate());
            shProductSpecs.setProductId(id);
            shProductSpecs.setProductSpecs(shProductSpecs.getSpecs());
            String ww =  shProductSpecs.getPrices();
            JSONObject jsons = JSONObject.parseObject(ww);
            Integer productStock = Integer.valueOf(jsons.getString("productStock"));
            String photo =  jsons.getString("photo");
            String productPrice =  jsons.getString("productPrice");
            shProductSpecs.setProductStock(productStock);
            shProductSpecs.setPhoto(photo);
            shProductSpecs.setProductPrice(new BigDecimal(productPrice));
        }
        shProductSpecsDao.insertSpects(list);
        return  Result.ok("添加成功");
    }




    /**
     * 修改数据
     *
     * @param shProduct 实例对象
     * @return 实例对象
     */
    @Override
    public Result update(ShProduct shProduct) {
        shProductDao.update(shProduct);
        return Result.ok("修改成功！");
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.shProductDao.deleteById(id) > 0;
    }

    /**
     * 根据商户id查询该商户发布的所有商品
     * @param businessId 商户id
     * @param page 页
     * @return
     */
    @Override
    public Result selectAllProduct(String businessId ,int page){
        PageHelper.startPage(page,10);
        List<ShProduct> shProductList =  shProductDao.queryByBusId(businessId);
        PageInfo<ShProduct> info = new PageInfo<ShProduct>(shProductList);
        return Result.ok(info);

    }

    /**
     * 根据商品id查询该商品详细信息
     * @param productId 商品id
     * @return
     */
    @Override
    public Result selectProductById1(String productId,HttpServletRequest request){
        //通过userId查询出用户名和用户表中的密码盐
        String name = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(name);
        ShProduct shProduct =  shProductDao.selectId(productId);
        if(shProduct != null){
            if(shProduct.getStatus().equals(0)){
                return Result.error("该商品已下架");
            }
            List<ShProductSpecs> specsList =  shProductSpecsDao.queryByProductId(productId);
            if(specsList.size()>0){
                for(ShProductSpecs shProductSpecs : specsList){
                    shProductSpecs.setProductPrice(shProductSpecs.getProductPrice().add(new BigDecimal(shProduct.getRebatePrice())));
                }
                shProduct.setShProductSpecs(specsList);
            }
            if(shUser == null || name == null){
                shProduct.setFollowState("0");
                shProduct.setCartNums("0");
            }else{
                Integer cartNums = shShopCartDao.selectCount(shUser.getId());
                shProduct.setCartNums(cartNums.toString());
                ShFollowProduct shFollowProduct = shFollowProductDao.selectProductAll(shUser.getId(),productId);
                if(shFollowProduct != null){
                    shProduct.setFollowState("1");
                }else {
                    shProduct.setFollowState("0");
                }
            }
            /*BigDecimal rebatePrice = new BigDecimal(shProduct.getRebatePrice());
            BigDecimal price = new BigDecimal(shProduct.getPrice());*/
            shProduct.setPrice(shProduct.getPrice() + shProduct.getRebatePrice());
            return Result.ok(shProduct);
        }else{
            return Result.error("未查询到该商品信息");
        }
    }

    /**
     * 后台根据商品id查询商品详细信息
     * @param productId
     * @return
     */
    @Override
    public Result selectProduct(String productId){
        ShProduct shProduct =  shProductDao.selectId(productId);
        if(shProduct != null){
            List<ShProductSpecs> specsList =  shProductSpecsDao.queryByProductId(productId);
            if(specsList.size()>0){
                shProduct.setShProductSpecs(specsList);
            }
            return Result.ok(shProduct);
        }else{
            return Result.error("未查询到该商品信息");
        }
    }

    /**
     * 随机从数据库中取6条数据
     * @return
     */
    @Override
    public Result selectRandProduct() {
        List<ShProduct> shProducts = shProductDao.selectRandProduct();
        if(shProducts.size() == 0 || shProducts == null){
            return Result.error("暂时没有任何商品信息");
        }
        return Result.ok(shProducts);
    }

    /**
     * 根据商品id和对应规格查询商品价格和库存情况
     * @param productId  商品id
     * @param productSpecs 商品规格
     * @return
     */
    @Override
    public Result selectSpecs(String productId ,String productSpecs){
        ShProductSpecs shProductSpecs =  shProductSpecsDao.selectSpecs(productId,productSpecs);
        return Result.ok(shProductSpecs);
    }

    /**
     * 添加商品新规格
     * @param
     * @param list
     * @return
     */
    @Override
    public Result insertSpecs(String shProductId, List<ShProductSpecs> list,List<ShopSpecs> shopSpecs) {
        String xx = "";
        for(ShopSpecs shopSpecs1 : shopSpecs){
            String a =  shopSpecs1.getChildren();
            String b= shopSpecs1.getType();
            xx = xx+","+ '"'+b +'"'+":"+a;
        }
        String str1=xx.substring(0, xx.indexOf(","));
        String str2=xx.substring(str1.length()+1, xx.length());
        ShProduct shProduct = shProductDao.selectId(shProductId);
        if(shProduct != null){
            shProduct.setAttributeList(str2);
            shProductDao.update(shProduct);
            for(ShProductSpecs shProductSpecs : list){
                shProductSpecs.setId(UUIDGenerator.generate());
                shProductSpecs.setProductId(shProductId);
                shProductSpecs.setProductSpecs(shProductSpecs.getSpecs());
                String ww =  shProductSpecs.getPrices();
                JSONObject jsons = JSONObject.parseObject(ww);
                Integer productStock = Integer.valueOf(jsons.getString("productStock"));
                String photo =  jsons.getString("photo");
                String productPrice =  jsons.getString("productPrice");
                shProductSpecs.setProductStock(productStock);
                shProductSpecs.setPhoto(photo);
                shProductSpecs.setProductPrice(new BigDecimal(productPrice));
            }
            return  Result.ok("添加成功");
        }else{
            return  Result.error("未查询到商品信息");
        }


    }

    /**
     * 根据各级分类id查询该分类下的所有商品
     * @param map
     * @return
     */
    @Override
    public Result listAll(Map map){
        List<ShProduct> shProductList =  shProductDao.queryAll(map);
        return Result.ok(shProductList);
    }

    /**
     * 后台查询商品列表
     * @param map
     * @return
     */
    @Override
    public Result queryList(Map map){
        Integer pagenum = (Integer) map.get("pagenum");
        Integer pagesize = (Integer) map.get("pagesize");
        int a = (pagenum-1)*pagesize;
        System.out.println(a);
        map.put("offset",a);
        map.put("limit",pagesize);
        List<ShProduct> shProductList =  shProductDao.queryList(map);
        Map map1 = new HashMap();
        ShProduct shProduct = shProductDao.selectCount(map);
        map1.put("total", shProduct.getSums());
        map1.put("shProductList",shProductList);
        return Result.ok(map1);
    }
    /**
     * 商品查询
     * type=1折扣最高,3新品上架按时间排序,4爆品抢购
     * @param map
     * @return
     */
    @Override
    public Result selectByList(Map map){
        List<ShProduct> shProductList =  shProductDao.selectByList(map);
        return Result.ok(shProductList);
    }

    /**
     * 快递查询
     * @param courierNum
     * @return
     */
    @Override
    public Result findCourier(String courierNum){
        System.out.println(courierNum);
        String json = RealUtil.market(courierNum);
        System.out.println(json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String status = jsonObject.get("status").toString();
        if(status == null){
            return Result.error(""+jsonObject);
        }
        if(status.equals("0")){
            String result = jsonObject.get("result").toString();
            JSONObject jsons = JSONObject.parseObject(result);
            return Result.ok(jsons);
        }else if(status.equals("201")){
            return Result.error("快递单号错误!!");
        }else if(status.equals("203")){
            return Result.error("快递公司不存在!!");
        }else if(status.equals("204")){
            return Result.error("快递公司识别失败!!");
        }else if(status.equals("205")){
            return Result.error("没有信息!!");
        }else{
            return Result.error("IP限制!!");
        }
    }


    /**
     * 后台用笛卡尔积算法分析数据，发布规格
     * @param listSub1
     * @param listSub2
     * @return
     */
    @Override
    public Result cartes(List<String> listSub1,List<String> listSub2) {
        List<List<String>> list = new ArrayList<List<String>>();
        list.add(listSub1);
        list.add(listSub2);
        List<List<String>> result = new ArrayList<List<String>>();
        descartes(list, result, 0, new ArrayList<String>());
        return Result.ok(result);
    }



    private static void descartes(List<List<String>> dimvalue, List<List<String>> result, int layer, List<String> curList) {
        if (layer < dimvalue.size() - 1) {
            if (dimvalue.get(layer).size() == 0) {
                descartes(dimvalue, result, layer + 1, curList);
            } else {
                for (int i = 0; i < dimvalue.get(layer).size(); i++) {
                    List<String> list = new ArrayList<String>(curList);
                    list.add(dimvalue.get(layer).get(i));
                    descartes(dimvalue, result, layer + 1, list);
                }
            }
        } else if (layer == dimvalue.size() - 1) {
            if (dimvalue.get(layer).size() == 0) {
                result.add(curList);
            } else {
                for (int i = 0; i < dimvalue.get(layer).size(); i++) {
                    List<String> list = new ArrayList<String>(curList);
                    list.add(dimvalue.get(layer).get(i));
                    result.add(list);
                }
            }
        }
    }

    /**
     * 查询店铺详细信息
     * @param businessId
     * @param userId
     * @return
     */
    @Override
    public Result queryByBusId(String businessId,String userId){
        ShMerchant shMerchant = shMerchantDao.queryById(businessId);
        if(shMerchant != null){
            List<ShProduct> shProductList =  shProductDao.queryByBusId(businessId);
            shMerchant.setProductList(shProductList);
            String shopNums =  shFollowShopDao.selectCount(businessId);
            if(shopNums != null){
                shMerchant.setShopNums(shopNums);
            }else{
                shMerchant.setShopNums("0");
            }

            ShFollowShop shFollowShop = shFollowShopDao.selectFollowShop(userId,businessId);
            if(shFollowShop != null){
                shMerchant.setFollowState("1");
            }else{
                shMerchant.setFollowState("0");
            }
            return Result.ok(shMerchant);
        }else{
            return Result.error("未查到店铺信息");
        }
    }

    /**
     * 管理系统查询店铺详细信息
     * @param
     * @return
     */
    @Override
    public Result selectByBusId(HttpServletRequest request){
        String name = JwtUtil.getUserNameByToken(request);
        ShBackUser shBackUser = shBackUserDao.selectLoginName(name);
        if(StringUtils.isBlank(name) || null == shBackUser){
            return Result.error("请先注册或者登录！");
        }
        String userId = shBackUser.getUserId();
        List<ShMerchant> shMerchantList = shMerchantDao.selectByUserId(userId);
        if(shMerchantList.size()>0){
            List<ShProduct> shProductList =  shProductDao.queryByBusId(shMerchantList.get(0).getId());
            shMerchantList.get(0).setProductList(shProductList);
            String shopNums =  shFollowShopDao.selectCount(shMerchantList.get(0).getId());
            if(shopNums != null){
                shMerchantList.get(0).setShopNums(shopNums);
            }else{
                shMerchantList.get(0).setShopNums("0");
            }
            return Result.ok(shMerchantList);
        }else{
            return Result.error("未查到店铺信息");
        }
    }
}
